//
// Created by yfux on 2022/4/18.
//

#include "JavaCallHelper.h"

JavaCallHelper::JavaCallHelper(JavaVM *pVm, JNIEnv *pEnv, jobject pJobject) : javaVm(pVm),
                                                                              env(pEnv) {
    jobj = env->NewGlobalRef(pJobject);
    jclass jclazz = env->GetObjectClass(jobj);
    jmid_error = env->GetMethodID(jclazz, "onError", "(I)V");
    jmid_prepare = env->GetMethodID(jclazz, "onPrepare", "(II)V");
    jmid_progress = env->GetMethodID(jclazz, "onProgress", "(I)V");
}

JavaCallHelper::~JavaCallHelper() {
    env->DeleteGlobalRef(jobj);
    jobj = 0;
}

void JavaCallHelper::onError(int code, int thread) {
    if (thread == THREAD_CHILD) {
        //子线程调用的
        JNIEnv *jniEnv;
        //先Attach
        if (javaVm->AttachCurrentThread(&jniEnv, 0) != JNI_OK) {
            return;
        }
        jniEnv->CallVoidMethod(jobj, jmid_error, code);
        //释放Attach
        javaVm->DetachCurrentThread();
    } else {
        //主线程调用的
        env->CallVoidMethod(jobj, jmid_error, code);
    }
}

void JavaCallHelper::onPrepare(int width, int height, int thread) {
    if (thread == THREAD_CHILD) {
        //子线程调用的
        JNIEnv *jniEnv;
        //先Attach
        if (javaVm->AttachCurrentThread(&jniEnv, 0) != JNI_OK) {
            return;
        }
        jniEnv->CallVoidMethod(jobj, jmid_prepare, width, height);
        //释放Attach
        javaVm->DetachCurrentThread();
    } else {
        //主线程调用的
        env->CallVoidMethod(jobj, jmid_prepare, width, height);
    }
}

void JavaCallHelper::onProgress(int progress, int thread) {
    if (thread == THREAD_CHILD) {
        //子线程调用的
        JNIEnv *jniEnv;
        //先Attach
        if (javaVm->AttachCurrentThread(&jniEnv, 0) != JNI_OK) {
            return;
        }
        jniEnv->CallVoidMethod(jobj, jmid_progress, progress);
        //释放Attach
        javaVm->DetachCurrentThread();
    } else {
        //主线程调用的
        env->CallVoidMethod(jobj, jmid_progress, progress);
    }
}